import { getCatalog } from "../../../api.js"
Page({
  /**
   * 页面的初始数据
   */
  $data: {
    oldIndex: 0
  },
  data: {
    view: "brandList",
    brandList: null,
    sideBar: [
      {
        value: "品牌",
        checked: true,
        view: "brandList"
      },
      {
        value: ""
      },
      {
        value: "包袋",
        type: "",
        id: 1
      },
      {
        value: "手表",
        type: "",
        id: 2
      },
      {
        value: "首饰",
        type: "",
        id: 3
      },
      {
        value: "配饰",
        type: "",
        id: 4
      }
    ],
    totalType: [{
      title: "箱包",
      children: [{
        id: 123,
        title: "手提包",
        picture: ""
      }]
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init();
  },
  init() {
    let xp = this;
    wx.getSystemInfo({
      success: (res) => {
        xp.setData({
          mainHeight: res.windowHeight - res.windowWidth / 750 * 15.5
        })
      }
    })
    xp.renderCatalog()
  },
  renderCatalog() {
    let businessId = getApp().globalData.Store.business.id
    getCatalog(businessId).then(res => {
      let data = res.data.data;
      this.setData({
        brandList: data[0].children,
        totalType: data[1].children
      })
    }).catch(err => {
    })

  },
  handleSideBarTap(e) {
    let { index, view, key } = e.target.dataset
    let checkKey = `sideBar[${index}]checked`
    if (index !== this.$data.oldIndex && index !== 1) {
      let oldKey = `sideBar[${this.$data.oldIndex}].checked`
      this.setData({
        [checkKey]: true,
        [oldKey]: false
      })
      this.$data.oldIndex = index
      this.toggleList(view, key)
    } else {
      return;
    }
  },
  // 切换列表
  toggleList(view, key) {
    let xp = this
    if (view === "brandList") {
      xp.setData({
        view
      })
    } else {
      let typeList = xp.data.totalType.filter(a => a.id === key)

      typeList = typeList[0] && typeList[0].children ? typeList[0].children : [];
      if (typeList.length % 3 === 2) {
        typeList.push({})
      }
      xp.setData({
        view: "typeList",
        typeList
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  onShow() {
    getApp().startpage(new Date().getTime())
  },
  onHide() {
    getApp().endpage(new Date().getTime())
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})